#include "textformatreader.h"
#include <QFile>

TextFormatReader::TextFormatReader(const QString &fileName, const QString &textCodecName)
{
    this->pTextCodec = QTextCodec::codecForName(textCodecName.toUtf8());

    this->fileName = fileName;
}

void TextFormatReader::openBook(const QString &filePath)
{
    QFile file(filePath);

    if (!file.exists())
    {
        emit this->error(FileNotFoundError);

        return;
    }

    if (!file.open(QIODevice::ReadOnly))
    {
        emit this->error(CanNotOpenFileError);

        return;
    }

    this->text = pTextCodec->toUnicode(file.readAll());

    file.close();
}

QString TextFormatReader::getFileName()
{
    return this->fileName;
}

QStringList TextFormatReader::countWords(QString text)
{
    QStringList words, buf;

    buf = text.split(" ");
    int c = buf.count();
    int maxWordLength = 0;

    for (int i = 0; i < c; i++)
    {
        if (buf.at(i) != "")
        {
            QString word = buf.at(i);
            words.append(word);

            if (word.count() > maxWordLength)
            {
                maxWordLength = word.count();
            }
        }
    }

    emit this->maxWordLength(maxWordLength);

    return words;
}
